package com.cy.sys.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cy.common.pojo.SysMenuList;
import com.cy.common.util.ShiroUtil;
import com.cy.sys.pojo.SysUser;
import com.cy.sys.service.SysUserService;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
/**
 * 此类进行页面的跳转的处理
 * @author private
 *
 */
@Controller
@RequestMapping("/")
public class PageController {
	@Autowired
	SysUserService sysUserService;
	@Autowired
	private Producer producer;
	/**
	 * 请求登录页面
	 */
	@RequestMapping("dologin")
	public String doLigin() {
		return "login";
	}
	
	/** 验证码请求地址 */
	@RequestMapping("kaptcha")
	public void doImage(HttpServletRequest request,HttpServletResponse response) {
		//获取session
		HttpSession session = request.getSession();
		ServletOutputStream out = null;
		//设置不使用缓存
		response.setHeader("Cache-Control", "no-store, no-cache");
		//设置返回为图片格式
		response.setContentType("image/jpeg");
		//基于producer生成文字
		String key = producer.createText();
		//后台测试使用检测验证码
		System.out.println(key);
		try {
			//基于文字生成图片验证码
			BufferedImage createImage = producer.createImage(key);
			//获取输出流
			out = response.getOutputStream();
			//在session中写入正确的验证码
			session.setAttribute(Constants.KAPTCHA_SESSION_KEY,key);
			//写入流
			ImageIO.write(createImage, "jpg", out);
			//流刷新
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(out!=null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	/**
	 * 请求剩下的所有页面
	 */
	@RequestMapping("{model}/{modelPage}")
	public String doModelUI(@PathVariable("modelPage") String modelPage) {
		System.out.println("???");
		return "sys/"+modelPage;
	}
	
	
	/**
	 * 请求主页starter
	 */
	@RequestMapping("doIndexUI")
	public String doIndexUI(Model model) {
		SysUser user = ShiroUtil.getUser();
		model.addAttribute("user", user);
		List<SysMenuList> menu = sysUserService.doGetMenusUrlByUserId(user.getId());
		model.addAttribute("menu",menu);
		return "starter";
	}
	
	/**
	 * 请求分页
	 */
	@RequestMapping("doPageUI")
	public String doPageUI() {
		return "common/page";
	}
}
